package com.sdry.realm;



import com.sdry.system.entity.SysUser;
import com.sdry.system.service.UserService;
import com.sdry.untils.BeanUtils;
import com.sdry.untils.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @version: 1.0
 * @description:
 * @author: cb
 * @create: 2020-01-13 16:46
 **/

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;



    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysUser sysUser = getSysUser();

        System.out.println(sysUser);

        return null;
    }

    /**
     * 验证身份
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String tokenUsername = token.getUsername();
        if (tokenUsername == null) {
            throw new AccountException("用户名为空......");
        }
        SysUser user = userService.queryUserByUserName(tokenUsername);
        if (user == null) {
            throw new UnknownAccountException("不存在这个用户......");
        }
        return new SimpleAuthenticationInfo(user,user.getPassword(),user.getUsername());
    }

    public static SysUser getSysUser()
    {
        SysUser user = null;
        Object obj = SecurityUtils.getSubject().getPrincipal();
        if (StringUtil.isNotNull(obj))
        {
            user = new SysUser();
            BeanUtils.copyBeanProp(user, obj);
        }
        return user;
    }
}
